//
//  ComposeViewController.swift
//  Weibo
//
//  Created by 孙成宇 on 15/12/3.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController {

 //MARK:监听方法
    @objc private func close () {

    dismissViewControllerAnimated(true, completion: nil)
    }



    @objc private func selectPicture() {
        textView.resignFirstResponder()

  selectorVC.view.snp_updateConstraints { (make) -> Void in
    make.height.equalTo(226 + 88 + 60)
        }

    }
    @objc  private func send () {
   var urlString = "https://api.weibo.com/2/statuses/update.json"
        let parmaters = ["access_token":userAccountViewModel().token,"status":textView.text]
          if selectorVC.imageList.count > 0 {


        urlString  = "https://upload.api.weibo.com/2/statuses/upload.json"
            let imageData = UIImagePNGRepresentation(selectorVC.imageList.first!)!


            NetworkTools.sharedTools.uploadImage(urlString, imageData: imageData, parameters: parmaters, finished: { (result, error) -> () in

                if error != nil {

                    SVProgressHUD.showErrorWithStatus(AppErrorTip)
                    return
                    
                }
         print(result)
        SVProgressHUD.showSuccessWithStatus("发布成功")
          self.dismissViewControllerAnimated(true, completion: nil)



            })



          }else {
             //没有图片 发送文本微博
            NetworkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parmaters) { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus(AppErrorTip)
                    return
                }
                print(result)
                SVProgressHUD.showSuccessWithStatus("发布成功")
                self.dismissViewControllerAnimated(true, completion: nil)
            }


        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
          setUpUI()
    }


    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
      if selectorVC.imageList.count == 0   {
        textView.becomeFirstResponder()
    }
    }


    private lazy var textView : UITextView = {
      let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        tv.backgroundColor  = UIColor.randomColor()
         tv.alwaysBounceVertical  = true

        tv.keyboardDismissMode = .OnDrag
        tv.delegate = self

        return tv


    }()
    private lazy var placeHolderText: UILabel = UILabel(title: "分享新鲜事", color: UIColor.lightGrayColor(), fontSize: 18, margin: 0)

    private lazy var toolBar = UIToolbar()

    private lazy var selectorVC: PictureSelectorViewController = PictureSelectorViewController()


    deinit{


    NSNotificationCenter .defaultCenter().removeObserver(self)
    }


}


extension ComposeViewController : UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {

        self.navigationItem.rightBarButtonItem?.enabled =
            textView.hasText()
placeHolderText.hidden = textView
        .hasText()

    }

}





extension  ComposeViewController {
    //MARK: 设置UI
    private func setUpUI () {

        view.backgroundColor  = UIColor.whiteColor()
        setNavBar()

        setTextView()

        setToolBar()

        reginsterNotilfication()

        setSelectorImageView()
    }
    private func setSelectorImageView() {


addChildViewController(selectorVC)
        view.addSubview(selectorVC.view)
        view.bringSubviewToFront(toolBar)
        selectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }



    }





    private func reginsterNotilfication() {

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWiiChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}



    @objc private func keyboardWiiChange(n: NSNotification) {

    let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as!Double
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue ).CGRectValue()


      let offset = -screenH + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)

        }
        UIView.animateWithDuration(duration) { () -> Void in

            self.view.layoutIfNeeded()

        }

    }



    private func setToolBar() {
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background"],
            ["imageName": "compose_add_background"]]

        var items = [UIBarButtonItem]()
        for dict in itemSettings {

            let btn = UIButton()
            btn.setImage(UIImage(named: dict["imageName"]!), forState: .Normal)
            btn.setImage(UIImage(named: dict["imageName"]! + "_highlighted"), forState: .Highlighted)

if let action = dict["actionName"]
{

   btn.addTarget(self, action: Selector(action), forControlEvents: .TouchUpInside)

            }


            btn.sizeToFit()
            let item = UIBarButtonItem(customView: btn)
            items.append(item)


            //添加弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        items.removeLast()

        toolBar.items = items


        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)

        view.addSubview(toolBar)


        //设置布局
        toolBar.snp_makeConstraints { (make) -> Void in
           make.bottom.left.right.equalTo(self.view)

//            make.bottom.equalTo(view.snp_bottom)
//            make.left.equalTo(view.snp_left)
//            make.right.equalTo(view.snp_right)
//

            make.height.equalTo(44)
        }
    }








    private func setTextView() {


        view.addSubview(textView)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(screenH / 3)
        }


        //添加占位文本
        textView.addSubview(placeHolderText)

        placeHolderText.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)

        }

    }


    //MARK: 设置导航栏
    private func setNavBar () {

        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")


        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        self.navigationItem.rightBarButtonItem?.enabled = false
        let v  = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))

        navigationItem.titleView = v

        let weiboLabel = UILabel(title: "发微博", color: UIColor.lightGrayColor(), fontSize: 17, margin: 0)


        let nameLabel = UILabel(title: userAccountViewModel().userName ?? "", color: UIColor.lightGrayColor(), fontSize: 14, margin: 0)


        v.addSubview(weiboLabel)

        v.addSubview(nameLabel)



        //
        weiboLabel.snp_makeConstraints { (make) -> Void in

            make.centerX.equalTo(v.snp_centerX)
            make.top.equalTo(v.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(v.snp_bottom)
            make.centerX.equalTo(v.snp_centerX)
            
        }
        
        
    }
    
    
    
    
}
